// 判断是不是一个路径
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

// 用户名验证
export function validUsername(str) {
  return hasContent(str)
}

// 密码验证
// 密码必须包含大小写字母、数字和特殊字符（长度大于6位）
export function validPassword(password) {
  const reg =
    /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{6,}/
  if (!reg.test(password)) {
    return false
  }
  return true
}

// 验证是否为空
export const hasContent = content => {
  return content.replace(/\ +/g, '').replace(/[\r\n]/g, '') !== ''
}

// 异步获取一个图片
export const loadImage = src => {
  return new Promise((resolve, reject) => {
    const imageObj = new Image()
    imageObj.onload = function () {
      resolve(imageObj)
    }
    imageObj.src = src
  })
}

// 单例实现画板页面
export const openDrawWindow = function (url) {
  window.DrawWindow =
    window.DrawWindow && !window.DrawWindow.closed
      ? window.DrawWindow
      : window.open('about:blank')
  window.DrawWindow.location.href = url
}

/**
 *
 * @param {Array} arrs 树形数据
 * @param {string} childs 树形数据子数据的属性名,常用'children'
 * @param {Array} attrArr 需要提取的公共属性数组(默认是除了childs的全部属性)
 * @returns
 */
export const extractTree = (arrs, childs = 'children', attrArr) => {
  let attrList = []
  if (!Array.isArray(arrs) && !arrs.length) return []
  if (typeof childs !== 'string') return []
  if (!Array.isArray(attrArr) || (Array.isArray(attrArr) && !attrArr.length)) {
    attrList = Object.keys(arrs[0])
    attrList.splice(attrList.indexOf(childs), 1)
  } else {
    attrList = attrArr
  }
  const list = []
  const getObj = (arr, id) => {
    arr.forEach(function (row) {
      const obj = {}
      attrList.forEach(item => {
        obj[item] = row[item]
      })
      obj.pid = id
      list.push(obj)
      if (row[childs]) {
        getObj(row[childs], row.id)
      }
    })
    return list
  }
  return getObj(arrs, null)
}

// 生成唯一id
export const genID = (length = 10) => {
  return Number(
    Math.random().toString().substr(3, length) + Date.now()
  ).toString(36)
}
